package com.z.xhelper.core.wx.hook;

import android.content.ContentValues;

import com.z.xhelper.core.config.BeanContainer;
import com.z.xhelper.core.eventbus.EventBus;
import com.z.xhelper.core.events.MsgReceiveEvent;
import com.z.xhelper.core.utils.LogUtil;

import java.util.Arrays;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;

/**
 * hook 文本消息
 */
public class MsgReceiveHook implements IHook {
    @Override
    public void hook() {
        ClassLoader classLoader = BeanContainer.getBean(ClassLoader.class);
        Class<?> aClass = XposedHelpers.findClass(
                "com.tencent.wcdb.database.SQLiteDatabase",
                classLoader);

        XposedHelpers.findAndHookMethod(
                aClass,
                "insertWithOnConflict",
                String.class,
                String.class,
                ContentValues.class,
                int.class,
                new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        if (!param.args[0].equals("message")) {
                            return;
                        }
                        // 微信版本 8.0.40
                        // 1 为文本消息 3为图片消息 34语音消息 43视频消息  47 表情 1090519089 文件
                        // 49 为分享链接（小程序、公众号都是）
                        // 只处理文本消息、图片消息、表情消息、视频消息、语音消息、文件消息
                        ContentValues contentValues = (ContentValues) param.args[2];
                        int type = contentValues.getAsInteger("type");
                        if (!Arrays.asList(1, 3, 34, 43, 47, 49, 1090519089).contains(type)) {
                            return ;
                        }
                        LogUtil.log("hook 收到文本消息：" + contentValues);
                        BeanContainer.getBean(EventBus.class)
                                .post(new MsgReceiveEvent(contentValues));
                    }
                }
        );
    }

}
